package com.srwl.mytx.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.srwl.mytx.R;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.Utils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MaxPriceRecordView extends LinearLayout {
    private Context context;
    //服务端返回的24小时的历史最高价记录
    private Map<String, Object> maxPriceRecord = new HashMap<>();
    //广告位默认价格0.1元 每个小时
    private final String commonPrice = "0.1";

    private BigDecimal offerAmount;
    private Date startDate;
    private Date endDate;
    private InteractionListener listener;

    @BindView(R.id.ll_hour_1)
    LinearLayout ll_hour1;
    @BindView(R.id.ll_hour_2)
    LinearLayout ll_hour2;
    @BindView(R.id.ll_hour_3)
    LinearLayout ll_hour3;
    @BindView(R.id.ll_hour_4)
    LinearLayout ll_hour4;

    public MaxPriceRecordView(Context context) {
        super(context);
        this.context = context;
        inflate(context, R.layout.max_price_view_layout, this);
        ButterKnife.bind(this);
        init();
    }

    public MaxPriceRecordView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        inflate(context, R.layout.max_price_view_layout, this);
        ButterKnife.bind(this);
        init();
    }

    public MaxPriceRecordView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        inflate(context, R.layout.max_price_view_layout, this);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        maxPriceRecord.clear();
        removeAllHourTextView();
        Date currentDate = new Date();
        BigDecimal price = new BigDecimal(commonPrice);
        for (int i = 0; i < 24; i++) {
            currentDate = DateUtils.addHour(currentDate, 1);
            String hh = DateUtils.dateToString(currentDate, "HH");
            String hourKey = DateUtils.dateToString(currentDate, "yyyy-MM-dd HH");
            maxPriceRecord.put(hourKey, price);
            if (hh.startsWith("0")) {
                hh = hh.substring(1);
            }
            String showContent = hh + "点";
            int greyColor = getResources().getColor(R.color.yancy_grey100);
            addHourTextView(i, showContent, price, greyColor);
        }
    }

    public void init(Map<String, Object> maxPriceRecord) {
        if (maxPriceRecord == null || maxPriceRecord.isEmpty()) {
            init();
        } else {
            this.maxPriceRecord = maxPriceRecord;
            generateGreyOfferRecordView();
        }
    }

    /**
     * 生成灰色的出价记录记录
     */
    public void generateGreyOfferRecordView() {
        removeAllHourTextView();
        Date currentDate = new Date();
        for (int i = 0; i < 24; i++) {
            currentDate = DateUtils.addHour(currentDate, 1);
            String hh = DateUtils.dateToString(currentDate, "HH");
            if (hh.startsWith("0")) {
                hh = hh.substring(1);
            }
            String hourKey = DateUtils.dateToString(currentDate, "yyyy-MM-dd HH");
            BigDecimal maxPrice = new BigDecimal(commonPrice);
            if (maxPriceRecord.containsKey(hourKey)) {
                Object maxPrice1 = maxPriceRecord.get(hourKey);
                if (maxPrice1 instanceof BigDecimal) {
                    maxPrice = (BigDecimal) maxPrice1;
                } else if (maxPrice1 instanceof Integer) {
                    maxPrice = new BigDecimal((Integer) maxPrice1);
                }
            }
            String showContent = hh + "点";
            int greyColor = getResources().getColor(R.color.yancy_grey100);
            addHourTextView(i, showContent, maxPrice, greyColor);
        }
    }

    public void generateMaxRecord(Date startDate, Date endDate) {
        this.startDate = startDate;
        this.endDate = endDate;
        generateMaxRecord();
    }

    public void generateMaxRecord(BigDecimal offerAmount) {
        this.offerAmount = offerAmount;
        generateMaxRecord();
    }


    public void generateMaxRecord() {
        if (maxPriceRecord == null || offerAmount == null || startDate == null || endDate == null) {
            return;
        }
        removeAllHourTextView();

        Date currentDate = new Date();
        //没有交集
        boolean noOverlap = false;
        //小于最高价
        boolean lessThan = false;
        //大于最高价
        boolean moreThan = false;
        for (int i = 0; i < 24; i++) {
            currentDate = DateUtils.addHour(currentDate, 1);
            String hh = DateUtils.dateToString(currentDate, "HH");
            if (hh.startsWith("0")) {
                hh = hh.substring(1);
            }
            String hourKey = DateUtils.dateToString(currentDate, "yyyy-MM-dd HH");
            BigDecimal maxPrice = new BigDecimal(commonPrice);
            if (maxPriceRecord.containsKey(hourKey)) {
                Object maxPrice1 = maxPriceRecord.get(hourKey);
                if (maxPrice1 instanceof BigDecimal) {
                    maxPrice = (BigDecimal) maxPrice1;
                } else if (maxPrice1 instanceof Integer) {
                    maxPrice = new BigDecimal((Integer) maxPrice1);
                }
            }
            String showContent = hh + "点";
            int color;

            //如果选择的时间段和当前遍历的时间段没有交集，设置textView的背景色为灰色
            if (startDate.after(currentDate) || endDate.before(currentDate)) {
                noOverlap = true;
                color = getResources().getColor(R.color.yancy_grey100);
            } else if (offerAmount.compareTo(maxPrice) > 0) {//如果我的出价高于当前时段最高价，设置textView的背景色为绿色
                moreThan = true;
                color = getResources().getColor(R.color.green);
            } else {//否则，设置textView的背景色为红色
                lessThan = true;
                color = getResources().getColor(R.color.red);
            }
            addHourTextView(i, showContent, maxPrice, color);
        }

        //投放时间段在24小之外，完全没有交集
        if (noOverlap && !moreThan && !lessThan) {
            if (listener != null) {
                listener.btnEnable(true);
            }
        } else if (moreThan) {//出价至少大于某一个时段
            if (listener != null) {
                listener.btnEnable(true);
            }
        } else {
            if (listener != null) {
                listener.btnEnable(false);
            }
        }


    }


    private void addHourTextView(int i, String time, BigDecimal price, int colorResourceId) {
        TimeAndPriceView timeAndPriceView = new TimeAndPriceView(context);
        timeAndPriceView.init(time, price);
        timeAndPriceView.setBackgroundColor(colorResourceId);
        LayoutParams layoutParams = new LayoutParams(0, LayoutParams.WRAP_CONTENT);
        layoutParams.weight = 1;
        int margin = Utils.dpToPx(1, context);
        layoutParams.leftMargin = margin;
        layoutParams.rightMargin = margin;
//        layoutParams.gravity = Gravity.CENTER;
//        timeAndPriceView.setGravity(Gravity.CENTER);
        timeAndPriceView.setLayoutParams(layoutParams);
        if (i < 6) {
            ll_hour1.addView(timeAndPriceView);
        } else if (i < 12) {
            ll_hour2.addView(timeAndPriceView);
        } else if (i < 18) {
            ll_hour3.addView(timeAndPriceView);
        } else {
            ll_hour4.addView(timeAndPriceView);
        }
    }


    public void removeAllHourTextView() {
        ll_hour1.removeAllViews();
        ll_hour2.removeAllViews();
        ll_hour3.removeAllViews();
        ll_hour4.removeAllViews();
    }

    public void resetBackground() {
        int greyColor = getResources().getColor(R.color.yancy_grey100);
        for (int i = 0; i < ll_hour1.getChildCount(); i++) {
            View child = ll_hour1.getChildAt(i);
            child.setBackgroundColor(greyColor);
        }
        for (int i = 0; i < ll_hour2.getChildCount(); i++) {
            View child = ll_hour2.getChildAt(i);
            child.setBackgroundColor(greyColor);
        }
        for (int i = 0; i < ll_hour3.getChildCount(); i++) {
            View child = ll_hour3.getChildAt(i);
            child.setBackgroundColor(greyColor);
        }
        for (int i = 0; i < ll_hour4.getChildCount(); i++) {
            View child = ll_hour4.getChildAt(i);
            child.setBackgroundColor(greyColor);
        }
    }

    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    public interface InteractionListener {
        void btnEnable(boolean enable);
    }


    public void refreshMaxPriceRecord(BigDecimal offerAmount) {
        this.offerAmount = offerAmount;
        //如果结束时间在24小时以后，则以一天后的时间点作为判断的结束点
        Date currentDate = new Date();
        Date addDays = DateUtils.addDays(currentDate, 1);
        if (endDate.after(addDays)) {
            endDate = addDays;
        }
        //循环判断 出价是否高于当前最高价，每循环一次，增加一个小时
        while (startDate.before(endDate)) {
            String maxPriceKey = DateUtils.dateToString(startDate, "yyyy-MM-dd HH");
            maxPriceRecord.put(maxPriceKey, offerAmount);
            //每循环一次，增加一个小时，
            startDate = DateUtils.addHour(startDate, 1);
        }
    }
}
